/*
 *Class Name:CreateMatterDialog
 *Class Function:
    *实现界面的UI
    *绑定goodsLineEidt的事件过滤器
    *绑定某些控件的信号至槽
*/

#include <QDebug>
#include <QAction>
#include <QMenu>
#include <QMessageBox>
#include <QStringList>

#include "creatematterdialog.h"
#include "ui_creatematterdialog.h"
#include "meatterdata.h"

static QTextStream cout(stdout);
CreateMatterDialog::CreateMatterDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::CreateMatterDialog),spendGoods("")
{
    ui->setupUi(this);

    //接下来为每个按钮创建对应的菜单构造函数

    //初始化三种控件的数据
    ui->spendDateTimeEdit->setDateTime(QDateTime::currentDateTime());
    ui->plainTextEdit->setPlainText(QString("\t\tSpend Message\nMoney: \nDate: \nGoods:"));
    initAllLabel();

    //连接两个控件的信号至槽
    connect(ui->spendDoubleSpinBox,SIGNAL(valueChanged(QString)),this,SLOT(createPainTextContent()));
    connect(ui->spendDateTimeEdit,SIGNAL(dateTimeChanged(QDateTime)),this,SLOT(createPainTextContent()));

    ui->goodsLineEdit->installEventFilter(this);


}

CreateMatterDialog::~CreateMatterDialog()
{
//    cout << "destruct" << endl;
    delete ui;
    ui = 0;
}

bool CreateMatterDialog::eventFilter(QObject *obj, QEvent *event)
{
    if (obj == ui->goodsLineEdit) {
        if (event->type() == QEvent::KeyPress) {
            QKeyEvent* keyEv = static_cast<QKeyEvent*>(event);
            if (keyEv->key() == Qt::Key_Backspace) {
                if (!spendGoods.isEmpty()) {
                    QStringList goodsList = spendGoods.split("|");
                    qDebug() << goodsList;
                    goodsList.removeLast();
                    qDebug() << goodsList;
                    spendGoods = goodsList.join("|");
                    ui->goodsLineEdit->setText(spendGoods);
                    createPainTextContent();
                }
                return true;
            }else {
                return false;
            }
        }

    }else {
        return QDialog::eventFilter(obj,event);
    }
}

//使用hideEvent代替closeEvent的原因是，保证对话框隐藏时，对话框的所有对象被释放。
void CreateMatterDialog::hideEvent(QHideEvent *)
{
    this->deleteLater();
}

//初始化所有Label，采用动态添加label的形式
void CreateMatterDialog::initAllLabel()
{
    QStringList textList;
    textList << "Apple"
              << "Banana"
              << "Peach"
              << "Pear"
              << "Pitaya"
              << "Orange";

    int var  =0;
    int textIndex = 0;
    for (int row = 0; row <= textList.count() / 4; ++row) {

        if (textList.count() > 4*(row+1))
            var = 4;
        else
            var = textList.count() - 4*row;
        for (int col = 0; col < var; ++col) {
            if (row == 0)
               textIndex = col;
            else
                textIndex = col+(row*4);

            Label * label = new Label(textList.at(textIndex));
            labelList.append(label);
            ui->LabelGridLayout->addWidget(label,row,col);
            connect(label,SIGNAL(mouseClick(QString)),this,SLOT(getGoods(QString)));
        }
    }



}
/*
QMenu *CreateMatterDialog::CreateEatMenus()
{
    QMenu* menu = new QMenu();

    //以下为水果项
    QMenu* fruitMenu = new QMenu("Fruit",this);

    QAction* apple = new QAction("Apple",this);
    QAction* orange = new QAction("orange",this);
    QAction* banana = new QAction("Banana",this);
    QAction* fruitOther  = new QAction("Other",this);

    QList<QAction*> fruitListAction;
    fruitListAction.append(apple);
    fruitListAction.append(orange);
    fruitListAction.append(banana);
    fruitListAction.append(fruitOther);

    //添加QList<QAction*>到fruit,并绑定信号槽
    fruitMenu->addActions(fruitListAction);
    foreach (QAction* action, fruitListAction) {
        connect(action,SIGNAL(triggered()),this,SLOT(getGoods(QString)));
    }

    QMenu* meals = new QMenu("Meals",this);
    QMenu* snacks = new QMenu("Snacks",this);
    QMenu* other = new QMenu("Other",this);

    menu->addMenu(fruitMenu);
    menu->addMenu(meals);
    menu->addMenu(snacks);
    menu->addMenu(other);

    return menu;

}*/

void CreateMatterDialog::getGoods(QString text)
{
    if (spendGoods.split("|").contains(text)) //不能重复包含相同的数据
        return;
    if (!spendGoods.isEmpty()) {
        spendGoods.append("|");
        spendGoods.append(text);
    }else {
        spendGoods.append(text);
    }
    createPainTextContent();
}


//初始化控件PainText
void CreateMatterDialog::createPainTextContent()
{
    ui->plainTextEdit->setPlainText( QString("\t\tSpend Message\nMoney: %1 RMB \nDate: %2 \nGoods: %3 ").arg(ui->spendDoubleSpinBox->text()).arg(ui->spendDateTimeEdit->dateTime().toString("yyyy-MM-dd ddd hh:mm:ss")).arg(spendGoods));
    ui->goodsLineEdit->setText(spendGoods);
}


void CreateMatterDialog::on_SaveOkPushButton_clicked()
{
    if(ui->spendDoubleSpinBox->isHidden()){
        this->close();
        return;
    }

    meatterData->WriteFile(ui->spendDateTimeEdit->dateTime().toString("yyyy-MM-dd ddd hh:mm:ss"),
                           ui->spendDoubleSpinBox->value(),
                           spendGoods);
    this->~CreateMatterDialog();
}


void CreateMatterDialog::SetData(QString itemText, bool isHidden)
{
    QStringList itemData = itemText.split(",");

    ui->spendDateTimeEdit->setDateTime(QDateTime::fromString(itemData.first(),"yyyy-MM-dd ddd hh:mm:ss"));//当发生段错误时，不一定都是参数的错误引用，也有可以是被赋值对象不存在而引起的非法操作内存。
    ui->spendDoubleSpinBox->setValue(itemData.at(1).toDouble());
    spendGoods = itemData.last();

    createPainTextContent();

    //隐藏不必需要显示的控件
    {
        ui->comboBox->setHidden(isHidden);
        ui->comboBox_2->setHidden(isHidden);

        foreach (Label* label, labelList) {
            label->setHidden(isHidden);
        }

        ui->label->setHidden(isHidden);
        ui->label_2->setHidden(true);
        ui->label_3->setHidden(isHidden);
        ui->label_4->setHidden(isHidden);
        ui->label_5->setHidden(isHidden);

        ui->goodsLineEdit->setHidden(isHidden);
        ui->spendDateTimeEdit->setHidden(isHidden);
        ui->spendDoubleSpinBox->setHidden(isHidden);
        ui->spendDateTimeEdit->setHidden(isHidden);

    }

}

//当goodsLineEdit不为空是，按钮可用
void CreateMatterDialog::on_goodsLineEdit_textChanged(QString arg1)
{
    ui->SaveOkPushButton->setEnabled(!arg1.isEmpty());
}


/*QTextCursor cursor=ui->textEdit->textCursor();//得到当前text的光标
if(cursor.hasSelection())//如果有选中，则取消，以免受受影响
cursor.clearSelection();
cursor.deletePreviousChar();//删除前一个字符
ui->textEdit->setTextCursor(cursor);//让光标移到删除后的位置
*/

